#!/usr/bin/evn python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name： ApiException
Description :
Author : 'Mark.Wei'
date： 2022/6/1
-------------------------------------------------
Change Activity:
2022/6/1:
-------------------------------------------------
"""
from typing import Any, Dict, Optional

from fastapi.encoders import jsonable_encoder
from starlette.responses import JSONResponse


class ApiResponse(JSONResponse):
    # 定义返回响应码--如果不指定的话则默认都是返回200
    status_code = 200
    success = True
    code = 0
    message = '操作成功'
    # 结果可以是{} 或 []
    data: Optional[Dict[str, Any]] = None

    def __init__(self, code: int = None, message: str = None,
                 data: Optional[Dict[str, Any]] = None, status_code: int = None, **options):

        if code and code != 0:
            self.success = False
            self.code = code

        if message:
            self.message = message

        if data:
            self.data = data

        if status_code:
            self.status_code = status_code

        # 返回结果
        body = dict(
            success=self.success,
            code=self.code,
            message=self.message,
            data=self.data
        )

        super(ApiResponse, self).__init__(status_code=self.status_code, content=jsonable_encoder(body), **options)
